import { useState, useEffect } from 'react'
// import axios from 'axios'
import { useNavigate } from 'react-router-dom'
import { useRecoilValue } from 'recoil'
import { applyForTopConfigType, applyForBottomConfigType, applyForDataType, pagingType } from '../interface/interface'
import { getUserAuditTableList, getSelectTree, getYearSelect, auditExport } from '../service/service'
import { userInfo } from '@/store/userInfo'
import { convertDataToCascaderFormat, findLabelByValue, isNullData } from '@/utils/index'
import { dictValuesSelector } from '@/store/dicts'
import { ExportExcel } from '@/utils/export'
// import { useRecoilValue } from 'recoil'
// import { userInfo } from '@/store/userInfo'
// const user = useRecoilValue(topUserInfo)
export default () => {
  const pushRouter = useNavigate()

  // 表格选中的序号集合
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([])
  // 选中序号事件
  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    // console.log('选中的序号集合: ', newSelectedRowKeys)
    setSelectedRowKeys(newSelectedRowKeys)
  }

  // 选中序号配置
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
    // onSelect: onSelectText,
    // onSelectAll: onSelectAllss,
  }

  // 分页信息
  const [paging, setPaging] = useState<pagingType>({
    pageSize: 10,
    pageIndex: 1,
    totalCount: 0,
  })
  // 申请加入审核顶部
  const [applyFor, setApplyFor] = useState({
    auditStatus: '',
    city: '',
    year: '',
    inputValue: '',
  })
  // 当前人的用户信息（主要是为了管理员的type）
  const user = useRecoilValue(userInfo)

  // 字典
  const dictValuesGet = useRecoilValue(dictValuesSelector)

  // 申请加入审核表格数据
  const [applyForTableData, setApplyForTableData] = useState([])

  // 选择的状态
  const [auditState, setAuditState] = useState<any>([])

  // 选择地区的级联数据
  const [auditPrevice, setAuditPrevice] = useState([])

  // 选择年份的下拉框数据
  const [yearSelector, setYearSelector] = useState([])

  // 获取选择状态
  const getApplyForStateValue = (value: string) => {
    setApplyFor({ ...applyFor, auditStatus: value })
  }

  // 获取地区
  const getApplyForCityValue = (value: any) => {
    // 此处判空 （ 下拉框点击取消按钮之后 ）
    if (!value) {
      setApplyFor({ ...applyFor, city: '' })
    } else {
      setApplyFor({ ...applyFor, city: value[value.length - 1] })
    }
  }

  // 获取年份
  const getApplyForYearValue = (value: string) => {
    setApplyFor({ ...applyFor, year: value })
  }

  // 获取输入框的值
  const getInputValue = (e: any) => {
    setApplyFor({ ...applyFor, inputValue: e.target.value })
  }

  // 获取表格数据
  const applyForData = async (filterPrevice: any) => {
    const params = {
      pageSize: paging.pageSize,
      pageIndex: paging.pageIndex,
      search: {
        hospitalNameOfApplyPeople: applyFor.inputValue || '',
        areaId: applyFor.city || '',
        auditStatus: applyFor.auditStatus || '', // 状态
        year: applyFor.year || '', // 年份
      },
      searchCount: true,
    }
    const res = await getUserAuditTableList(params)
    if (isNullData(res)) {
      // 表格数据发生改变重新set表格总数据
      setPaging({ ...paging, totalCount: res.data.totalCount })

      // if (res.data.items.length === 0) {
      //   setPaging({ ...paging, pageIndex: 1 })
      // }

      // 处理所属地区数字转文字
      res.data.items.forEach((item: applyForDataType) => {
        const hospitalAreaArray = [item.hospitalArea]
        const result = hospitalAreaArray[0].split(',').map(Number)
        let depoistFont = ''
        for (let i = 0; i < result.length; i++) {
          const label = findLabelByValue(filterPrevice, result[i])
          depoistFont += `${label}/`
          // hospitalAreaFilterFont 转化为文字的字段
          item.hospitalAreaFilterFont = depoistFont
        }
        // 拼接定级和定等
        const findHospitalRating = dictValuesGet.hospital_rating?.find(
          (itemFind: any) => itemFind.value === item.hospitalRating,
        )
        const findRank = dictValuesGet.hospital_level?.find(
          (itemHospitalLevel: any) => itemHospitalLevel.value === item.hospitalLevel,
        )
        item.gradingAndGrading = `${findRank.label}${findHospitalRating.label}`
      })
      setApplyForTableData(res.data.items)
    }
  }

  // 分页切换
  const changePagingUploadTable = (page: number, pageSizes: number) => {
    setPaging({
      ...paging,
      pageIndex: page,
      pageSize: pageSizes,
    })
  }

  // 输入框的回车事件
  const enterApplyForInput = () => {
    applyForData(auditPrevice)
  }

  // 申请加入审核的导出数据
  const applyForExport = async () => {
    // 全部导出的 ids
    const tableIds = applyForTableData.reduce((acc: any, cur: any) => {
      acc.push(cur.id)
      return acc
    }, [])

    if (selectedRowKeys.length === 0) {
      const res = await auditExport(tableIds)
      const excleName = '用户申请审核全部数据'
      ExportExcel(res, excleName)
      return
    }

    if (selectedRowKeys.length > 0) {
      const res = await auditExport(selectedRowKeys)
      const excleName = '用户申请审核部分数据'
      ExportExcel(res, excleName)
    }
  }

  // 转换文字函数，返回label 做数据渲染
  const returnLable = (params1: any, params2: string | number) =>
    params1?.find((item: { value: string; label: string }) => item.value === params2).label

  // 点击审核跳转到审核页面
  const applyForRouterPush = (record: any) => {
    // 拷贝原始没有被枚举的整条对象
    const originalRecord = { ...record }

    // 转换医院`
    const hospitalAreaArray = [record.hospitalArea]
    const result = hospitalAreaArray[0].split(',').map(Number)
    let depoistFont = ''
    for (let i = 0; i < result.length; i++) {
      const label = findLabelByValue(auditPrevice, result[i])
      depoistFont += `${label}/`
      record.hospitalArea = depoistFont.substring(0, depoistFont.length - 1)
    }

    // 转换医院定级
    record.hospitalLevel = returnLable(dictValuesGet.hospital_level, record.hospitalLevel)

    // 转换医院定等
    record.hospitalRating = returnLable(dictValuesGet.hospital_rating, record.hospitalRating)

    // 转换医院类别
    record.hospitalType = returnLable(dictValuesGet.hospital_type, record.hospitalType)

    // 转换是否教学医院
    record.isTeachHospital = returnLable(dictValuesGet.is_teach_hospital, record.isTeachHospital)

    // 转换医院性质
    record.hospitalNature = returnLable(dictValuesGet.hospital_nature, record.hospitalNature)

    const params = {
      recordValue: record, // 枚举之后的整条数据
      originalRecordValue: originalRecord, // 未被枚举的整条数据
    }
    pushRouter('/user-admin-province/joinAduitApplyFor', { state: params })
  }

  // 动态获取地区树形结构
  const getCitySelectorData = async () => {
    let ifSignUserLocationId: any = 0
    if (user.accountType === 10) {
      ifSignUserLocationId = user.provinceId
    }
    if (user.accountType === 20) {
      ifSignUserLocationId = user.cityId
    }
    const res = await getSelectTree({ signUserLocationId: ifSignUserLocationId })
    if (isNullData(res)) {
      const filterPrevice = convertDataToCascaderFormat(res.data)
      setAuditPrevice(filterPrevice)
      await applyForData(filterPrevice)
      console.log('🦢🦢', filterPrevice)
    }
  }

  // 获取用户审核年份下拉框
  const getUsetYearSelector = async () => {
    const res = await getYearSelect()
    console.log('🦢🦢', res.data)
    const yearDataReconsitution = res.data.reduce((acc: any, cur: any) => {
      acc.push({ value: cur, label: cur })
      return acc
    }, [])
    setYearSelector(yearDataReconsitution)
  }

  const init = async () => {
    await getCitySelectorData()
    await setAuditState(dictValuesGet.platform_join_hospital_audit_status) // 字段里面的状态
    await getUsetYearSelector()
  }

  useEffect(() => {
    init()
  }, [])

  useEffect(() => {
    applyForData(auditPrevice)
  }, [applyFor.auditStatus, applyFor.city, applyFor.year, paging.pageIndex, paging.pageSize])

  // 申请审核顶部配置
  const applyForTopConfig: applyForTopConfigType = {
    getApplyForStateValue,
    getApplyForCityValue,
    getApplyForYearValue,
    getInputValue,
    enterApplyForInput,
    applyForExport,
    auditPrevice,
    auditState,
    yearSelector,
  }

  // 申请审核表格配置
  const applyForBottomConfig: applyForBottomConfigType = {
    applyForTableData,
    applyForRouterPush,
    rowSelection,
    changePagingUploadTable,
    paging,
  }

  return {
    applyForTopConfig,
    applyForBottomConfig,
  }
}
